/*   The MIT License
 *   
 *   Carina Engine
 *   Copyright (c) 2009 2010 2011 2012 Zdravko Velinov
 *   
 *   Permission is hereby granted, free of charge, to any person obtaining a copy
 *   of this software and associated documentation files (the "Software"), to deal
 *   in the Software without restriction, including without limitation the rights
 *   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *   copies of the Software, and to permit persons to whom the Software is
 *   furnished to do so, subject to the following conditions:
 *
 *   The above copyright notice and this permission notice shall be included in
 *   all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *   THE SOFTWARE.
 */

#ifndef FILTERS_H_
#define FILTERS_H_

#include "carina/math.hh"
#include "carina/common/assert.hh"

namespace Carina
{
void sobel_filter(const float* in, Vector4* out, unsigned w, unsigned h);

template<class T>
T bilinear_filter(float px, float py, const T* in, unsigned w, unsigned h)
{
    CE_ASSERT(0.0f <= px && px <= 1.0f && 0.0f <= py && py <= 1.0f, "Clamping is not supported by this function.");
    px *= w, py *= h;
    int x1 = (int)floor(px);
    int y1 = (int)floor(py);
    int x2 = (int)ceil(px);
    int y2 = (int)ceil(py);
    float u1 = px - x1;
    float v1 = py - y1;
    float u2 = 1 - u1;
    float v2 = 1 - v1;
    return (in[y1*w + x1]*u2 + in[y1*w + x2]*u1)*v2 + (in[y2*w + x1]*u2 + in[y2*w + x2]*u1)*v1;
}
}
#endif /* FILTERS_H_ */
